/*
 * 客户权限设备账号管理视图
 * @Author: ljb
 * @Date: 2018-03-27 17:52:07
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-09-26 09:36:22
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>
    .v-customer-device-account-views {
		padding: 20px;
		.account-tabpane {
			min-height: 74vh;
		}
    }
</style>

<template>

	<div class="v-customer-device-account-views">

		<Tabs
			type="card"
			@on-click="changeTab">

			<TabPane
				v-if="canAddAccount"
				:label="$t('common.create')"
				name="新增">

				<account-create
					ref="create"
					@post="postData"/>

			</TabPane>

			<TabPane
				:label="$t('common.check')"
				class="account-tabpane"
				name="查看">

				<!-- 搜索组件 -->
				<search-form @search="confirmSearch"/>

				<account-index
					:loading="table_loading"
					:accounts="device_accounts.data"
					@edit="deviceAccountDetail"
					@enabled="enabledDeviceAccount"
					@disabled="disableDeviceAccount"
					@sort="confirmSearch"/>

				<br>

				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="device_accounts.total"
						:current="device_accounts.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>

				</Row>

			</TabPane>
		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('device.update_account')"
			class-name="vertical-middle-modal">

			<!-- 账号编辑组件 -->
			<account-edit
				:stores="stores"
				:device-account-detail="account_detail"
				@update="updateDviceAccount"/>

			<div slot="footer"/>

		</Modal>

	</div>

</template>

<script>

import qs from 'qs';
import { mapGetters, mapMutations } from 'vuex';
import API_LIST from 'src/API_LIST';
import { $t } from 'src/i18n/index';
import accountCreate from './create';
import accountIndex from './index';
import accountEdit from './edit';
import searchForm from './search-form';

const BUY_SOFTWARE = 3; // 购买软件的客户的type

export default {

	name: 'DeviceAccountViews',

	components: {
		accountCreate,

		accountIndex,

		accountEdit,

		searchForm,
	},
	data() {
		return {
			query_info: {
				page: 1,

				per_page: 20,

				keyword: '',
			}, // 页码

			search_info: {
				page: 1,

				per_page: 20,
			}, // 分页信息

			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			skin_detectors: [], // 设备信息

			account_detail: {}, // 账号详情

			device_accounts: {}, // 设备账号列表

			stores: [], // 店铺信息

		};
	},
	computed: {
		...mapGetters('userToken', [
			'getUserInfo',
		]),

		canAddAccount() {
			const { provider_type } = this.getUserInfo;

			if (Number(provider_type) === BUY_SOFTWARE) {
				return true;
			}

			this.changeTab('查看');

			return false;
		},
	},
	mounted() {
		this.fetchStoreAndDevice();
	},
	methods: {

		...mapMutations('spinShow', [
			'showSpin',
			'closeSpin',
		]),

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			if (tab_name === '查看') {
				this.fetchDeviceAccountList(this.query_info);
			} else {
				this.device_accounts.data = [];
			}
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchDeviceAccountList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchDeviceAccountList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch(param) {
			this.query_info.keyword = param.keyword;

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchDeviceAccountList(this.query_info);
		},

		/**
         * 新增账号的post数据
		 * @param {Object} param {表单数据}
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUST_DEVICE_ACCOUNT, param)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');
				})
				.catch((err) => {
					this.$Message.error(err.message);
				})
				.then(this.closeSpin);
		},

		/**
         * 查看账号详情
         * @param  {string} id {合作伙伴的id}
         * @return {undefined}
         */
		deviceAccountDetail(account) {
			this.account_detail = account;

			this.show_modal = true;
		},

		/**
         * 更新设备账号信息
         * @param  {Object} param {需要更新的参数对象}
         * @return {undefined}
         */
		updateDviceAccount(id, param) {
			this.showSpin();

			this.$http.post(`${API_LIST.CUST_DEVICE_ACCOUNT}/${id}`, param)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.show_modal = false;

					this.fetchDeviceAccountList(this.search_info);
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 启用账号
         * @param  {string} id {操作的id}
         * @return {undefined}
         */
		enabledDeviceAccount(row) {
			const param = {

				enabled: 1,

			};

			this.table_loading = true;

			this.$http.patch(`${API_LIST.CUSTOMER_DEVICE_ENABLED}/${row.id}`, param)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('device.start_success'));
					/* eslint-disable-next-line no-param-reassign */
					row.enabled = true;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},

		/**
         * 禁用账号
         * @param  {string} id {需要禁用的账号的id}
         * @return {undefined}
         */
		disableDeviceAccount(row) {
			this.$Modal.confirm({
				title: this.$t('device.is_disable_account'), // '确定禁用此账号么？',
				onOk: () => {
					const param = {
						enabled: 0,
					};

					this.table_loading = true;

					this.$http.patch(`${API_LIST.CUSTOMER_DEVICE_ENABLED}/${row.id}`, param)
						.then(({ data }) => {
							if (Number(data.code) !== 0) throw new Error(data.error);

							this.$Message.success(this.$t('device.enable_success'));
							/* eslint-disable-next-line no-param-reassign */
							row.enabled = false;
						})
						.catch((err) => {
							this.$Message.error(err.message || err.statusText);
						})
						.then(() => { this.table_loading = false; });
				},
				onCancel: () => {},
			});
		},

		/**
         * 获取店铺信息以及设备信息
         * @return {undefined}
         */
		fetchStoreAndDevice() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.get(`${API_LIST.CUST_DEVICE_ACCOUNT}/create`)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.stores = data.stores;

					const new_obj = {

						id: '0',

						name: $t('common.none'), // '无', // TODO: ?
					};

					this.stores.unshift(new_obj);

					this.skin_detectors = data.skin_detectors;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},


		/**
         * 获取设备账号列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchDeviceAccountList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(param);

			this.$http.get(`${API_LIST.CUST_DEVICE_ACCOUNT}?${query_str}`)
				.then(({ data }) => {
					if (Number(data.code) !== 0) throw new Error(data.error);

					this.device_accounts = data.device_accounts;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},
	},
};
</script>
